package com.rong.shop.controller;

import com.rong.shop.pojo.Address;
import com.rong.shop.service.IAddressService;
import com.rong.shop.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/addresses")
public class AddressController extends BaseController{

    @Autowired
    private IAddressService addressService;

    @RequestMapping("/addAddress")
    @ResponseBody
    public JsonResult<Void> addAddress(HttpSession session, Address address){

        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);

        addressService.addAddress(uid, username, address);
        return new JsonResult<Void>(OK);
    }

    @RequestMapping("/findByUid")
    @ResponseBody
    public JsonResult<List<Address>> findByUid(HttpSession session){

        Integer uid = getUidFromSession(session);
        List<Address> datas = addressService.findByUid(uid);
        return new JsonResult<List<Address>>(OK,datas);
    }

////  http://localhost:8080/addresses/findByAid/22
//    @RequestMapping("/findByAid/{aid}")
//    public String findByAid(Integer aid, HttpSession session){
//        Address address = addressService.findByAid(aid);
//        session.setAttribute("address",address);
//        System.out.println("hello");
//        return "updateAddress";
//    }

    @RequestMapping("/setDefault/{aid}")
    @ResponseBody
    public JsonResult<Void> setDefault(HttpSession session,@PathVariable("aid") Integer aid){

        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        addressService.setDefault(aid, uid, username);
        return new JsonResult<Void>(OK);
    }


    @RequestMapping("/deleteByAid/{aid}")
    @ResponseBody
    public JsonResult<Void> deleteByAid(HttpSession session, @PathVariable("aid") Integer aid){

        Integer uid = getUidFromSession(session);
        addressService.deleteByAid(aid, uid);
        return new JsonResult<>(OK);
    }


}
